package com.tuling.fox._05.jucdemo.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Fox
 */
public class CASTest {

    public static void main(String[] args) {
        Entity entity = new Entity();

        AtomicInteger atomicX = new AtomicInteger(entity.x);

        boolean successful;

        // 4个参数分别是：对象实例、字段的内存偏移量、字段期望值、字段更新值
        successful = atomicX.compareAndSet(0, 3);
        System.out.println(successful + "\t" + atomicX.get());

        successful = atomicX.compareAndSet(3, 5);
        System.out.println(successful + "\t" + atomicX.get());

        successful = atomicX.compareAndSet(3, 8);
        System.out.println(successful + "\t" + atomicX.get());
    }

//    public static void main1(String[] args) {
//        Entity entity = new Entity();
//
//        // CAS 在 Unsafe 类中，使用时 UnsafeFactory 获取 Unsafe 对象
//        Unsafe unsafe = UnsafeFactory.getUnsafe();
//
//        // 获取字段的内存偏移量 才能使用 CAS
//        long offset = UnsafeFactory.getFieldOffset(unsafe, Entity.class, "x");
//        System.out.println(offset);
//        boolean successful;
//
//        // 4个参数分别是：对象实例、字段的内存偏移量、字段期望值、字段更新值
//        successful = unsafe.compareAndSwapInt(entity, offset, 0, 3);
//        System.out.println(successful + "\t" + entity.x);
//
//        successful = unsafe.compareAndSwapInt(entity, offset, 3, 5);
//        System.out.println(successful + "\t" + entity.x);
//
//        successful = unsafe.compareAndSwapInt(entity, offset, 3, 8);
//        System.out.println(successful + "\t" + entity.x);
//
//    }


}


class Entity{
    int x;
}
